// storageUtils.ts

/**
 * 存储类型枚举
 */
export enum StorageType {
  LOCAL = 'localStorage',
  SESSION = 'sessionStorage',
}

/**
 * 获取存储对象
 * @param type 存储类型
 * @returns Storage对象
 */
export const getStorage = (type: StorageType): Storage => {
  return type === StorageType.LOCAL ? localStorage : sessionStorage
}

/**
 * 设置存储项
 * @param type 存储类型
 * @param key 键名
 * @param value 值
 */
export const setItem = <T>(type: StorageType, key: string, value: T): void => {
  const storage = getStorage(type)
  try {
    const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value)
    storage.setItem(key, stringValue)
  } catch (error) {
    console.error('Storage设置失败:', error)
  }
}

/**
 * 获取存储项
 * @param type 存储类型
 * @param key 键名
 * @param defaultValue 默认值
 * @returns 存储的值或默认值
 */
export const getItem = <T>(type: StorageType, key: string, defaultValue?: T): T | null => {
  const storage = getStorage(type)
  try {
    const value = storage.getItem(key)
    if (value === null) {
      return defaultValue ?? null
    }
    try {
      return JSON.parse(value) as T
    } catch {
      return value as unknown as T
    }
  } catch (error) {
    console.error('Storage获取失败:', error)
    return defaultValue ?? null
  }
}

/**
 * 移除存储项
 * @param type 存储类型
 * @param key 键名
 */
export const removeItem = (type: StorageType, key: string): void => {
  const storage = getStorage(type)
  try {
    storage.removeItem(key)
  } catch (error) {
    console.error('Storage删除失败:', error)
  }
}

/**
 * 清空存储
 * @param type 存储类型
 */
export const clearStorage = (type: StorageType): void => {
  const storage = getStorage(type)
  try {
    storage.clear()
  } catch (error) {
    console.error('Storage清空失败:', error)
  }
}

/**
 * 获取所有键名
 * @param type 存储类型
 * @returns 键名数组
 */
export const getAllKeys = (type: StorageType): string[] => {
  const storage = getStorage(type)
  try {
    return Object.keys(storage)
  } catch (error) {
    console.error('获取所有键名失败:', error)
    return []
  }
}
